package com.hong.spring.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author: csh
 * @Date: 2020/12/18 16:03
 * @Description:nacos配置
 */
@Configuration
@EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
public class NacosConfig  {

    @NacosInjected
    private NamingService namingService;

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${server.port}")
    private Integer serverPort;


    @PostConstruct
    public void init() {
        // 通过Naming服务注册实例到注册中心
        try {
            namingService.registerInstance(applicationName, "${nacos.config.host}", serverPort);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
